package com.atguigui.leetcode;

import java.util.Arrays;

/**
 * 396.旋转函数
 * <p>
 * Project: leetcode
 * Package: com.atguigui.leetcode
 * Version: 1.0
 * <p>
 * Created by WJX on 2022/4/22 8:40
 */
public class P396RotateFunction {
    public static void main(String[] args) {
        Solution solution = new P396RotateFunction().new Solution();
        // TO TEST
        int[] num = {4, 3, 2, 6};
        System.out.println(solution.maxRotateFunction(num));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {

        //暴力破解：时间超时
        public int maxRotateFunction(int[] nums) {
            int ans = Integer.MIN_VALUE;

            //旋转次数
            int numRotate = nums.length;


            for (int i = 0; i < numRotate; i++) {
                int sum = 0;
                //第一次不用旋转直接计算
                if (i == 0) {
                    for (int j = 0; j < nums.length; j++) {
                        sum += nums[j] * j;
                    }
                } else {
                    //旋转数组
                    for (int j = 0; j < nums.length - 1; j++) {
                        int last = nums[nums.length - 1 - j];
                        nums[nums.length - 1 - j] = nums[nums.length - 1 - 1 - j];
                        nums[nums.length - 1 - 1 - j] = last;
                    }

                    //计算
                    for (int j = 0; j < nums.length; j++) {
                        sum += nums[j] * j;
                    }
                }
                ans = Math.max(ans, sum);
            }


            return ans;
        }


        //F(0)=0×nums[0]+1×nums[1]+…+(n−1)×nums[n−1]
        //F(1)=1×nums[0]+2×nums[1]+…+0×nums[n−1]=F(0)+numSum−n×nums[n−1]
        //F(2)=2xnums[0]+3xnums[1]+...+1xnums[n-1]=F(1)+numSum - n x nums[n-1]
        public int maxRotateFunction2(int[] nums) {


            int f = 0;
            int n = nums.length;

            //所有的第一个  1 x nums[n] 的和
            int numSum = Arrays.stream(nums).sum();

            for (int i = 0; i < n; i++) {
                f += i * nums[i];
            }

            int ans = f;
            for (int i = n - 1; i > 0; i--) {
                f += numSum - n * nums[i];
                ans = Math.max(ans, f);
            }


            return ans;
        }

    }
}
